/**********************************************************
Filename: i2c-net.cpp
Author: Dave Frank (dnfrank@gmail.com)

**********************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include "i2cNet.h"
#include "revision_info.h"
const unsigned long i2cNet::REV_NUMBER=SVN_REV;
const std::string i2cNet::REV_URL=SVN_URL;
const std::string i2cNet::REV_DATE=SVN_DATE;



i2cNet::i2cNet(const std::string& name):
m_name(name),
m_fd(-1)
{
}

i2cNet::~i2cNet()
{
	if(connected())
	{
		disconnect();
	}
}

i2cNet::Status i2cNet::connect()
{
    i2cNet::Status retval=FAILURE;
    if(!connected())
    {
        m_fd=::open(m_name.c_str(),O_RDWR);
        if(m_fd!=-1)
        {
            retval=SUCCESS;
        }
    }
    else
    {
        retval=SUCCESS;
    }
    return retval;
}

i2cNet::Status i2cNet::disconnect()
{
    i2cNet::Status retval=SUCCESS;
    if(connected())
    {
        ::close(m_fd);
        m_fd=-1;
    }
    else
    {
        retval=NOT_OPEN;
    }
}

bool i2cNet::connected()
{
    return (m_fd!=-1);
}


i2cNet::Status i2cNet::addDevice(i2cDevice& device)
{
    i2cNet::Status retval=i2cNet::FAILURE;
    if(device!=i2cDevice::NULL_DEVICE)
    {
        if(!device.m_network)
        {
            i2cDevice oldDevice=getDevice(device.name());
            if(oldDevice==i2cDevice::NULL_DEVICE)
            {
                device.m_network=this;
	        m_devices[device.name()]=device;
                retval=SUCCESS;
            }
        }
    }
    return retval;
}

i2cNet::Status i2cNet::removeDevice(const std::string& name)
{
    i2cNet::Status retval=i2cNet::FAILURE;
    std::map<std::string,i2cDevice>::iterator itr = m_devices.find(name);
    if(itr!=m_devices.end())
    {
        m_devices.erase(itr);
        retval=i2cNet::SUCCESS;
    }
    return retval;
}

i2cNet::Status i2cNet::removeDevice(const i2cDevice& device)
{
    return removeDevice(device.name());
}

i2cDevice i2cNet::getDevice(const std::string& name)
{
    i2cDevice device;
    if(!m_devices.empty())
    {
    	std::map<std::string,i2cDevice>::iterator itr = m_devices.find(name);
        if(m_devices.end()!=itr)
        {
    	    device =  itr->second;
        }
    }
    return device;
}
 
CREATE_SVN_REV_FUNCTION(i2cNet);
void i2cNet::printRevisionInfo(std::ostream& out)
{
    CALL_SVN_REV_FUNCTION(i2cNet,NULL,NULL);
    out << "I2C Network Libray Revision Info." << std::endl;
    out << "    Revision Number: " << REV_NUMBER <<  std::endl;
    out << "    Revision URL:    " << REV_URL <<  std::endl;
    out << "    Revision Date:   " << REV_DATE <<  std::endl;
}
